﻿using Domain.Entitys.Inv;
using Domain.Entitys.Sinv;
using Domain.IRepositorys.Sinv;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Domain.Entitys.Sinv.Sinv_Sale_Return_Info;

namespace EFCore.Repositorys.Sinv
{
    public class Sinv_Sale_OrderRepository : ISinv_Sale_OrderRepository
    {
        private readonly MyDbContext myDbContext;

        public Sinv_Sale_OrderRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        /// <summary>
        /// 查询销售订单及其详情
        /// </summary>
        /// <param name="currendPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="customerName"></param>
        /// <param name="orderCode"></param>
        /// <returns></returns>
        public List<Sinv_Sale_Order_Info> GetSinv_Sale_Infos(int currendPage, int pageSize, string customerName, string orderCode, string proName, int orderStatus, char auditStatus)
        {
            IQueryable<Sinv_Sale_Order> query = myDbContext.Sinv_Sale_Order;
            query = query.Where(so => so.Del_flag == '0').OrderByDescending(so => so.Create_time).ThenByDescending(so => so.Update_time);

            if (!string.IsNullOrEmpty(customerName))
            {
                query = query.Where(so => so.Customer_name.Contains(customerName) || so.Customer_code.Contains(customerName));
            }
            if (!string.IsNullOrEmpty(orderCode))
            {
                query = query.Where(so => so.Sale_order_code.Contains(orderCode));
            }
            if (!string.IsNullOrEmpty(proName))
            {
                var detailIds = myDbContext.Sinv_Sale_Order_Details
                    .Where(d => d.Pro_name.Contains(proName) || d.Pro_code.Contains(proName))
                    .Select(d => d.Sale_order_id);
                query = query.Where(so => detailIds.Contains(so.Sale_order_id));
            }
            if (orderStatus != -1)
            {
                query = query.Where(s => s.Sale_order_status == orderStatus);
            }
            if (auditStatus == '0' || auditStatus == '1' || auditStatus == '2')
            {
                query = query.Where(s => s.Sale_order_audit_status == auditStatus);
            }
            if (currendPage != 0 && pageSize != 0)
            {
                query = query.Skip((currendPage - 1) * pageSize).Take(pageSize);
            }
            var result = query
                .Select(so => new Sinv_Sale_Order_Info
                {
                    Sale_order_id = so.Sale_order_id,
                    Sale_order_name = so.Sale_order_name,
                    Customer_code = so.Customer_code,
                    Sale_order_code = so.Sale_order_code,
                    Customer_name = so.Customer_name,
                    Sale_order_deliver_time = so.Sale_order_deliver_time,
                    Sale_order_sign_time = so.Sale_order_sign_time,
                    Sale_order_status = so.Sale_order_status,
                    Sale_order_audit_status = so.Sale_order_audit_status,
                    Sale_order_total_price = so.Sale_order_total_price,
                    Sale_order_total_proce = so.Sale_order_total_proce,
                    Sale_order_total_qty = so.Sale_order_total_qty,
                    Contacts_name = so.Contacts_name,
                    Contacts_phone = so.Contacts_phone,
                    Create_by = so.Create_by,
                    Create_time = so.Create_time,
                    Sale_order_dept_id = so.Sale_order_dept_id,
                    Sale_order_rep_id = so.Sale_order_rep_id,
                    Details = so.Details
                    .Select(details => new Sinv_Sale_Order_Info.Sinv_Sale_Order_Details
                    {
                        Sale_order_details_id = details.Sale_order_details_id,
                        Sale_order_code = details.Sale_order_code,
                        Pro_name = details.Pro_name,
                        Pro_code = details.Pro_code,
                        Pro_brand = details.Pro_brand,
                        Pro_model = details.Pro_model,
                        Measure_id = details.Measure_id,
                        Pro_sale_qty = details.Pro_sale_qty,
                        Pro_cost_price = details.Pro_cost_price,
                        Pro_sale_price = details.Pro_sale_price,
                        Pro_total_amount = details.Pro_total_amount,
                        Pro_return_qty = details.Pro_return_qty,
                        Pro_total_cost = details.Pro_total_cost,
                        Pro_planned_return_qty = details.Pro_planned_return_qty,
                        Pro_outbound_qty = details.Pro_outbound_qty,
                        Pro_planned_outbound_qty = details.Pro_planned_outbound_qty
                    }).ToList()
                }).ToList();
            return result;
        }

        /// <summary>
        /// 根据客户名称、销售订单名称、产品名称查询汇总
        /// </summary>
        /// <param name="customerName"></param>
        /// <param name="saleOrserName"></param>
        /// <param name="proName"></param>
        /// <returns></returns>
        public List<Sinv_Sale_Order_Info> GetSinv_Sale_InfosSummary(string customerName, string saleOrserName, string proName)
        {
            IQueryable<Sinv_Sale_Order> query = myDbContext.Sinv_Sale_Order;
            query = query.Where(so => so.Del_flag == '0' && so.Sale_order_audit_status == '1');
            if (!string.IsNullOrEmpty(customerName))
            {
                query = query.Where(so => so.Customer_name.Contains(customerName) || so.Customer_code.Contains(customerName));
            }
            if (!string.IsNullOrEmpty(saleOrserName))
            {
                query = query.Where(so => so.Sale_order_name.Contains(saleOrserName) || so.Sale_order_code.Contains(saleOrserName));
            }
            var result = query.OrderBy(so => so.Update_time)
                .ThenBy(so => so.Create_time).AsNoTracking().Select(so => new Sinv_Sale_Order_Info
                {
                    Sale_order_id = so.Sale_order_id,
                    Sale_order_name = so.Sale_order_name,
                    Customer_code = so.Customer_code,
                    Sale_order_code = so.Sale_order_code,
                    Customer_name = so.Customer_name,
                    Sale_order_deliver_time = so.Sale_order_deliver_time,
                    Sale_order_sign_time = so.Sale_order_sign_time,
                    Sale_order_status = so.Sale_order_status,
                    Sale_order_audit_status = so.Sale_order_audit_status,
                    Sale_order_total_price = so.Sale_order_total_price,
                    Sale_order_total_proce = so.Sale_order_total_proce,
                    Sale_order_total_qty = so.Sale_order_total_qty,
                    Details = so.Details
                    .Where(d => string.IsNullOrEmpty(proName) || d.Pro_name.Contains(proName) || d.Pro_code.Contains(proName))
                    .Select(details => new Sinv_Sale_Order_Info.Sinv_Sale_Order_Details
                    {
                        Sale_order_details_id = details.Sale_order_details_id,
                        Sale_order_code = details.Sale_order_code,
                        Pro_name = details.Pro_name,
                        Pro_code = details.Pro_code,
                        Pro_brand = details.Pro_brand,
                        Pro_model = details.Pro_model,
                        Measure_id = details.Measure_id,
                        Pro_sale_qty = details.Pro_sale_qty,
                        Pro_cost_price = details.Pro_cost_price,
                        Pro_sale_price = details.Pro_sale_price,
                        Pro_total_amount = details.Pro_total_amount,
                        Pro_return_qty = details.Pro_return_qty,
                        Pro_total_cost = details.Pro_total_cost,
                        Pro_outbound_qty = details.Pro_outbound_qty,
                        Pro_planned_outbound_qty = details.Pro_planned_outbound_qty,
                        Pro_planned_return_qty = details.Pro_planned_return_qty,

                    }).ToList()
                }).ToList();
            return result;
        }

        /// <summary>
        /// 根据销售订单编号查询对应销售订单信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<Sinv_Sale_Order> GetSinv_Sale_OrderByCodeAsync(string code)
        {
            return await myDbContext.Sinv_Sale_Order.FirstOrDefaultAsync(so => so.Sale_order_code == code);
        }

        /// <summary>
        /// 分页条件查询销售订单明细
        /// </summary>
        /// <param name="currentId"></param>
        /// <param name="pageSize"></param>
        /// <param name="code"></param>
        /// <param name="productCode"></param>
        /// <param name="measureId"></param>
        /// <returns></returns>
        public async Task<List<Sinv_Sale_Order_Details>> GetSinv_Sale_Order_DetailsAsync(int currentPage, int pageSize, string code, string productCode, int measureId)
        {
            IQueryable<Sinv_Sale_Order_Details> sinv_Sale_Order_Details = myDbContext.Sinv_Sale_Order_Details
                .Where(sod => sod.Sale_order_code == code);
            if (!string.IsNullOrEmpty(productCode))
            {
                sinv_Sale_Order_Details = sinv_Sale_Order_Details.Where(sod => sod.Pro_code == productCode);
            }
            if (measureId != 0)
            {
                sinv_Sale_Order_Details = sinv_Sale_Order_Details.Where(sod => sod.Measure_id == measureId);
            }
            return await sinv_Sale_Order_Details.Skip((currentPage - 1) * pageSize).Take(pageSize).ToListAsync();
        }

        /// <summary>
        /// 根据销售订单编号查询销售明细
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<List<Sinv_Sale_Order_Details>> GetSinv_Sale_Order_DetailsByCodeAsync(string code)
        {
            return await myDbContext.Sinv_Sale_Order_Details.Where(sod => sod.Sale_order_code == code).ToListAsync();
        }

        /// <summary>
        /// 条件查询销售订单明细总数
        /// </summary>
        /// <param name="code"></param>
        /// <param name="productCode"></param>
        /// <param name="measureId"></param>
        /// <returns></returns>
        public async Task<int> GetSinv_Sale_Order_DetailsCountAsync(string code, string productCode, int measureId)
        {
            IQueryable<Sinv_Sale_Order_Details> sinv_Sale_Order_Details = myDbContext.Sinv_Sale_Order_Details
                .Where(sod => sod.Sale_order_code == code);
            if (!string.IsNullOrEmpty(productCode))
            {
                sinv_Sale_Order_Details = sinv_Sale_Order_Details.Where(sod => sod.Pro_code == productCode);
            }
            if (measureId != 0)
            {
                sinv_Sale_Order_Details = sinv_Sale_Order_Details.Where(sod => sod.Measure_id == measureId);
            }
            return await sinv_Sale_Order_Details.CountAsync();
        }

        /// <summary>
        /// 添加销售订单信息和销售明细
        /// </summary>
        /// <param name="sinv_Sale_Order">销售订单</param>
        /// <param name="sinv_Sale_Order_Details">销售详情</param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OrderAddAsync(Sinv_Sale_Order sinv_Sale_Order, List<Sinv_Sale_Order_Details> sinv_Sale_Order_Details)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                //添加主表记录
                await myDbContext.AddAsync(sinv_Sale_Order);
                await myDbContext.SaveChangesAsync();
                //为销售详情表设置外键
                foreach (var item in sinv_Sale_Order_Details)
                {
                    item.Sale_order_id = sinv_Sale_Order.Sale_order_id;
                    item.Sale_order_code = sinv_Sale_Order.Sale_order_code;
                }

                //批量添加销售订单明细
                await myDbContext.Sinv_Sale_Order_Details.AddRangeAsync(sinv_Sale_Order_Details);
                await myDbContext.SaveChangesAsync();

                ////增加销售预计出库数量
                //var proCodes = sinv_Sale_Order_Details.Select(d => d.Pro_code).Distinct().ToList();
                //var stocks = await myDbContext.inv_stock
                //    .Where(s => proCodes.Contains(s.pro_code))
                //    .ToDictionaryAsync(s => s.pro_code);

                ////增加销售预计出库数量
                //foreach (var item in sinv_Sale_Order_Details)
                //{
                //    stocks[item.Pro_code].Stock_planned_outbound_qty += item.Pro_sale_qty;
                //    myDbContext.Entry(stocks[item.Pro_code]).State = EntityState.Modified; // 显式标记
                //}
                //await myDbContext.SaveChangesAsync();

                //如果全部添加成功则提交事务
                await transaction.CommitAsync();
                return 1;
            }
            catch (Exception)
            {
                //回滚事务
                await transaction.RollbackAsync();
                return 0;
            }
        }

        /// <summary>
        /// 修改销售订单审核状态，增加库存预计出库数量
        /// </summary>
        /// <param name="sinv_Sale_Order"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OrderAuditUpdateAsync(Sinv_Sale_Order sinv_Sale_Order)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                //修改销售订单审核状态
                Sinv_Sale_Order sinv_Sale_Order1 = await myDbContext.Sinv_Sale_Order
                    .FirstOrDefaultAsync(so => so.Sale_order_id == sinv_Sale_Order.Sale_order_id);
                sinv_Sale_Order1.Sale_order_audit_by = sinv_Sale_Order.Sale_order_audit_by;
                sinv_Sale_Order1.Sale_order_audit_time = sinv_Sale_Order.Sale_order_audit_time;
                sinv_Sale_Order1.Sale_order_audit_status = sinv_Sale_Order.Sale_order_audit_status;
                sinv_Sale_Order1.Sale_order_audit_opinion = sinv_Sale_Order.Sale_order_audit_opinion;
                myDbContext.Update(sinv_Sale_Order1);
                await myDbContext.SaveChangesAsync();

                //查询销售订单明细
                var details = myDbContext.Sinv_Sale_Order_Details.Where(s => s.Sale_order_id == sinv_Sale_Order1.Sale_order_id);
                //审核通过时增加预计出库数量、驳回则不增加预计出库数量
                if (sinv_Sale_Order1.Sale_order_audit_status == '1')
                {
                    //增加销售预计出库数量
                    var proCodes = details.Select(d => d.Pro_code).Distinct().ToList();
                    var stocks = await myDbContext.inv_stock
                        .Where(s => proCodes.Contains(s.pro_code))
                        .GroupBy(x => x.pro_code)
                        .Select(g => g.OrderBy(x => x.Create_Time).First())//升序排序多组重复记录每组取第一条
                        .ToDictionaryAsync(s => s.pro_code);

                    //增加销售预计出库数量
                    foreach (var item in details)
                    {
                        stocks[item.Pro_code].Stock_planned_outbound_qty += item.Pro_sale_qty;
                        myDbContext.Entry(stocks[item.Pro_code]).State = EntityState.Modified; // 显式标记
                    }
                    await myDbContext.SaveChangesAsync();
                }
                // 3. 为每个商品分配库存
                //foreach (var item in details)
                //{
                //    decimal remainingQty = item.Pro_planned_outbound_qty; // 待出库数量

                //    // 按入库时间升序获取库存位置（先进先出）
                //    var stocks = await myDbContext.inv_stock
                //        .Where(s => s.pro_code == item.Pro_code && s.stock_numder > 0)
                //        .OrderBy(s => s.Create_Time) // 关键：按入库时间排序
                //        .ToListAsync();

                //    foreach (var stock in stocks)
                //    {
                //        if (remainingQty <= 0) break; // 当前商品已分配完毕

                //        decimal availableQty = stock.stock_numder - stock.Stock_planned_outbound_qty;
                //        if (availableQty <= 0) continue; // 当前库存位置无可分配量

                //        // 计算本次分配量
                //        decimal allocateQty = Math.Min(availableQty, remainingQty);
                //        stock.Stock_planned_outbound_qty += allocateQty; // 更新计划出库量
                //        remainingQty -= allocateQty; // 减少待分配量

                //        myDbContext.Entry(stock).State = EntityState.Modified;
                //    }

                //    // 若仍有剩余数量，说明库存不足（可记录错误或抛出异常）
                //    if (remainingQty > 0)
                //    {
                //        throw new Exception($"库存不足！商品 {item.Pro_code} 缺 {remainingQty} 件");
                //    }
                //}
                await transaction.CommitAsync();

                return 1;
            }
            catch (Exception)
            {
                await transaction.RollbackAsync();
                return 0;
            }
        }

        /// <summary>
        /// 查询销售订单总数
        /// </summary>
        /// <param name="customerName"></param>
        /// <param name="orderCode"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OrderCOuntAsync(string customerName, string orderCode, string proName, int orderStatus, char auditStatus)
        {
            IQueryable<Sinv_Sale_Order> query = myDbContext.Sinv_Sale_Order.Where(so => so.Del_flag == '0');
            if (!string.IsNullOrEmpty(customerName))
            {
                query = query.Where(so => so.Customer_name.Contains(customerName) || so.Customer_code.Contains(customerName));
            }
            if (!string.IsNullOrEmpty(orderCode))
            {
                query = query.Where(so => so.Sale_order_code.Contains(orderCode));
            }
            if (!string.IsNullOrEmpty(proName))
            {
                var detailQuery = myDbContext.Sinv_Sale_Order_Details
                    .Where(d => d.Pro_code.Contains(proName) || d.Pro_name.Contains(proName))
                    .Select(d => d.Sale_order_id);

                query = query.Where(so => detailQuery.Contains(so.Sale_order_id));
            }
            if (orderStatus != -1)
            {
                query = query.Where(s => s.Sale_order_status == orderStatus);
            }
            if (auditStatus == '0' || auditStatus == '1' || auditStatus == '2')
            {
                query = query.Where(s => s.Sale_order_audit_status == auditStatus);
            }
            return await query.CountAsync();
        }

        /// <summary>
        /// 逻辑删除销售订单信息
        /// </summary>
        /// <param name="sinv_Sale_Order"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OrderDelAsync(Sinv_Sale_Order sinv_Sale_Order)
        {
            Sinv_Sale_Order sinv_Sale_Order1 = await myDbContext.Sinv_Sale_Order.FirstOrDefaultAsync(so => so.Sale_order_id == sinv_Sale_Order.Sale_order_id);
            sinv_Sale_Order1.Del_flag = sinv_Sale_Order.Del_flag;
            myDbContext.Sinv_Sale_Order.Update(sinv_Sale_Order1);
            return await myDbContext.SaveChangesAsync();
            //using var transaction = await myDbContext.Database.BeginTransactionAsync();
            //try
            //{
            //    //修改销售订单删除状态
            //    Sinv_Sale_Order sinv_Sale_Order1 = await myDbContext.Sinv_Sale_Order.FirstOrDefaultAsync(so => so.Sale_order_id == sinv_Sale_Order.Sale_order_id);
            //    sinv_Sale_Order1.Del_flag = sinv_Sale_Order.Del_flag;
            //    myDbContext.Sinv_Sale_Order.Update(sinv_Sale_Order1);

            //    List<Sinv_Sale_Order_Details> sinv_sale_order_details = myDbContext.Sinv_Sale_Order_Details
            //        .Where(s => s.Sale_order_code == sinv_Sale_Order1.Sale_order_code).ToList();


            //    //减少销售预计出库数量
            //    var proCodes = sinv_sale_order_details.Select(d => d.Pro_code).Distinct().ToList();
            //    var stocks = await myDbContext.inv_stock
            //        .Where(s => proCodes.Contains(s.pro_code))
            //        .ToDictionaryAsync(s => s.pro_code);

            //    //减少销售预计出库数量
            //    foreach (var item in sinv_sale_order_details)
            //    {
            //        stocks[item.Pro_code].Stock_planned_outbound_qty -= item.Pro_sale_price;
            //        myDbContext.Entry(stocks[item.Pro_code]).State = EntityState.Modified; // 显式标记
            //    }

            //    await myDbContext.SaveChangesAsync();
            //    await transaction.CommitAsync();

            //    return 1;
            //}
            //catch (Exception)
            //{
            //    await transaction.RollbackAsync();
            //    return 0;
            //}
        }

        /// <summary>
        /// 销售订单撤销，修改订单审核状态，减少预计出库数量
        /// </summary>
        /// <param name="sinv_Sale_Order"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OrderRevokeAsync(Sinv_Sale_Order sinv_Sale_Order)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                //修改订单审核状态
                Sinv_Sale_Order sinv_Sale_Order1 = await myDbContext.Sinv_Sale_Order
                    .FirstOrDefaultAsync(s => s.Sale_order_id == sinv_Sale_Order.Sale_order_id);
                sinv_Sale_Order1.Sale_order_audit_status = sinv_Sale_Order.Sale_order_audit_status;

                //查询销售订单明细
                var details = myDbContext.Sinv_Sale_Order_Details.Where(s => s.Sale_order_id == sinv_Sale_Order1.Sale_order_id);
                //减少销售预计出库数量
                var proCodes = details.Select(d => d.Pro_code).Distinct().ToList();
                var stocks = await myDbContext.inv_stock
                    .Where(s => proCodes.Contains(s.pro_code))
                    .GroupBy(x => x.pro_code)
                    .Select(g => g.OrderBy(x => x.Create_Time).First())//升序排序多组重复记录每组取第一条
                    .ToDictionaryAsync(s => s.pro_code);

                //减少销售预计出库数量
                foreach (var item in details)
                {
                    stocks[item.Pro_code].Stock_planned_outbound_qty -= item.Pro_sale_qty;
                    myDbContext.Entry(stocks[item.Pro_code]).State = EntityState.Modified; // 显式标记
                }
                await myDbContext.SaveChangesAsync();

                await transaction.CommitAsync();
                return 1;
            }
            catch (Exception)
            {
                await transaction.RollbackAsync();
                return 0;
            }
        }

        /// <summary>
        /// 分页条件查询销售订单信息
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderCode"></param>
        /// <param name="status"></param>
        /// <param name="customerName"></param>
        /// <param name="rep_id"></param>
        /// <param name="dept_id"></param>
        /// <returns></returns>
        public async Task<List<Sinv_Sale_Order>> Sinv_Sale_OrderSelectAsync(int currentPage, int pageSize, string orderCode, int status, string customerName, int rep_id, int dept_id)
        {
            IQueryable<Sinv_Sale_Order> sinv_Sale_Orders = myDbContext.Sinv_Sale_Order.Where(s => s.Del_flag == '0' && s.Sale_order_audit_status == '1' && s.Sale_order_status != 2 && s.Sale_order_status != 4);
            if (!string.IsNullOrEmpty(orderCode))
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_code.Contains(orderCode));
            }
            if (status > -1)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_status == status);
            }
            if (!string.IsNullOrEmpty(customerName))
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Customer_code.Contains(customerName));
            }
            if (rep_id != 0)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_rep_id == rep_id);
            }
            if (dept_id != 0)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_dept_id == dept_id);
            }
            return await sinv_Sale_Orders.OrderByDescending(s => s.Create_time).Skip((currentPage - 1) * pageSize).Take(pageSize).ToListAsync();
        }

        /// <summary>
        /// 条件查询销售订单总数
        /// </summary>
        /// <param name="orderCode"></param>
        /// <param name="status"></param>
        /// <param name="customerName"></param>
        /// <param name="rep_id"></param>
        /// <param name="dept_id"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OrderSelectCountAsync(string orderCode, int status, string customerName, int rep_id, int dept_id)
        {
            IQueryable<Sinv_Sale_Order> sinv_Sale_Orders = myDbContext.Sinv_Sale_Order.Where(s => s.Del_flag == '0' && s.Sale_order_audit_status == '1' && s.Sale_order_status != 2 && s.Sale_order_status != 4);
            if (!string.IsNullOrEmpty(orderCode))
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_code.Contains(orderCode));
            }
            if (status > -1)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_status == status);
            }
            if (!string.IsNullOrEmpty(customerName))
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Customer_code.Contains(customerName));
            }
            if (rep_id != 0)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_rep_id == rep_id);
            }
            if (dept_id != 0)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_dept_id == dept_id);
            }
            return await sinv_Sale_Orders.CountAsync();
        }

        /// <summary>
        /// 分页条件查询出库销售订单信息
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderCode"></param>
        /// <param name="status"></param>
        /// <param name="customerName"></param>
        /// <param name="rep_id"></param>
        /// <param name="dept_id"></param>
        /// <returns></returns>
        public async Task<List<Sinv_Sale_Order>> Sinv_Sale_OrderSelectFillAsync(int currentPage, int pageSize, string orderCode, int status, string customerName, int rep_id, int dept_id)
        {
            IQueryable<Sinv_Sale_Order> sinv_Sale_Orders = myDbContext.Sinv_Sale_Order.Where(s => s.Del_flag == '0' && s.Sale_order_audit_status == '1' && s.Sale_order_status != 4);
            if (!string.IsNullOrEmpty(orderCode))
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_code.Contains(orderCode));
            }
            if (status > -1)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_status == status);
            }
            if (!string.IsNullOrEmpty(customerName))
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Customer_code.Contains(customerName));
            }
            if (rep_id != 0)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_rep_id == rep_id);
            }
            if (dept_id != 0)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_dept_id == dept_id);
            }
            return await sinv_Sale_Orders.OrderByDescending(s => s.Create_time).Skip((currentPage - 1) * pageSize).Take(pageSize).ToListAsync();
        }

        /// <summary>
        /// 条件查询出库销售订单总数
        /// </summary>
        /// <param name="orderCode"></param>
        /// <param name="status"></param>
        /// <param name="customerName"></param>
        /// <param name="rep_id"></param>
        /// <param name="dept_id"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OrderSelectFillCountAsync(string orderCode, int status, string customerName, int rep_id, int dept_id)
        {
            IQueryable<Sinv_Sale_Order> sinv_Sale_Orders = myDbContext.Sinv_Sale_Order.Where(s => s.Del_flag == '0' && s.Sale_order_audit_status == '1' && s.Sale_order_status != 4);
            if (!string.IsNullOrEmpty(orderCode))
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_code.Contains(orderCode));
            }
            if (status > -1)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_status == status);
            }
            if (!string.IsNullOrEmpty(customerName))
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Customer_code.Contains(customerName));
            }
            if (rep_id != 0)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_rep_id == rep_id);
            }
            if (dept_id != 0)
            {
                sinv_Sale_Orders = sinv_Sale_Orders.Where(s => s.Sale_order_dept_id == dept_id);
            }
            return await sinv_Sale_Orders.CountAsync();
        }

        /// <summary>
        /// 修改销售订单信息
        /// </summary>
        /// <param name="sinv_Sale_Order"></param>
        /// <param name="sinv_Sale_Order_Details"></param>
        /// <returns></returns>
        public async Task<int> Sinv_Sale_OrderUpdateAsync(Sinv_Sale_Order sinv_Sale_Order, List<Sinv_Sale_Order_Details> sinv_Sale_Order_Details)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                //修改销售订单信息
                Sinv_Sale_Order sinv_Sale_Order1 = await myDbContext.Sinv_Sale_Order
                    .FirstOrDefaultAsync(so => so.Sale_order_id == sinv_Sale_Order.Sale_order_id);
                sinv_Sale_Order1.Sale_order_name = sinv_Sale_Order.Sale_order_name;
                sinv_Sale_Order1.Sale_order_code = sinv_Sale_Order.Sale_order_code;
                sinv_Sale_Order1.Customer_name = sinv_Sale_Order.Customer_name;
                sinv_Sale_Order1.Customer_code = sinv_Sale_Order.Customer_code;
                sinv_Sale_Order1.Contacts_name = sinv_Sale_Order.Contacts_name;
                sinv_Sale_Order1.Contacts_phone = sinv_Sale_Order.Contacts_phone;
                sinv_Sale_Order1.Sale_order_sign_time = sinv_Sale_Order.Sale_order_sign_time;
                sinv_Sale_Order1.Sale_order_audit_time = sinv_Sale_Order.Sale_order_audit_time;
                sinv_Sale_Order1.Sale_order_rep_id = sinv_Sale_Order.Sale_order_rep_id;
                sinv_Sale_Order1.Sale_order_dept_id = sinv_Sale_Order.Sale_order_dept_id;
                sinv_Sale_Order1.Update_by = sinv_Sale_Order.Update_by;
                sinv_Sale_Order1.Update_time = sinv_Sale_Order.Update_time;
                myDbContext.Update(sinv_Sale_Order1);
                await myDbContext.SaveChangesAsync();

                //查询数据库中的旧销售订单明细
                var oldDetails = await myDbContext.Sinv_Sale_Order_Details
                    .AsNoTracking()
                    .Where(s => s.Sale_order_code == sinv_Sale_Order1.Sale_order_code).ToListAsync();

                //识别三类记录
                var toAdd = new List<Sinv_Sale_Order_Details>();//新增明细
                var toUpdate = new List<Sinv_Sale_Order_Details>();//更新明细
                var toDel = new List<int>();//删除明细id
                //var netChangeDict = new Dictionary<string, decimal>(); // <sale_order_details_id, 净变化量>

                foreach (var newItem in sinv_Sale_Order_Details)
                {
                    //新记录：无主键或主键不在旧列表中
                    if (newItem.Sale_order_details_id == 0
                        || !oldDetails.Any(old => old.Sale_order_details_id == newItem.Sale_order_details_id))
                    {
                        toAdd.Add(newItem);
                    }
                    else
                    {
                        var oldItem = oldDetails.First(old => old.Sale_order_details_id == newItem.Sale_order_details_id);
                        if (IsModified(oldItem, newItem))
                        {
                            toUpdate.Add(newItem);
                        }
                    }
                }

                toDel = oldDetails.Where(old => !sinv_Sale_Order_Details.Any(newItem => newItem.Sale_order_details_id == old.Sale_order_details_id))
                    .Select(old => old.Sale_order_details_id).ToList(); // 错误：使用错误ID字段

                // 批量删除旧明细
                if (toDel.Any())
                {
                    var delItems = oldDetails.Where(d => toDel.Contains(d.Sale_order_details_id));
                    myDbContext.RemoveRange(delItems);
                }

                //更新变化的明细
                foreach (var item in toAdd)
                {
                    item.Sale_order_code = sinv_Sale_Order1.Sale_order_code;
                    item.Sale_order_id = sinv_Sale_Order1.Sale_order_id;
                    await myDbContext.AddAsync(item);
                }

                foreach (var updateItem in toUpdate)
                {
                    var existingDetail = oldDetails.FirstOrDefault(d => d.Sale_order_details_id == updateItem.Sale_order_details_id);
                    if (existingDetail != null)
                    {
                        existingDetail.Pro_sale_qty = updateItem.Pro_sale_qty;
                        existingDetail.Pro_sale_price = updateItem.Pro_sale_price;
                        existingDetail.Pro_total_amount = updateItem.Pro_total_amount;
                        existingDetail.Pro_cost_price = updateItem.Pro_cost_price;
                        existingDetail.Pro_total_cost = updateItem.Pro_total_cost;
                        myDbContext.Update(existingDetail);
                    }
                }

                await myDbContext.SaveChangesAsync();

                // 处理删除的明细：减少出库量
                //foreach (var delItem in oldDetails.Where(d => toDel.Contains(d.Sale_order_details_id)))
                //{
                //    if (!netChangeDict.ContainsKey(delItem.Pro_code))
                //        netChangeDict[delItem.Pro_code] = 0;
                //    netChangeDict[delItem.Pro_code] -= delItem.Pro_sale_price;
                //}

                //// 处理新增明细：增加出库量
                //foreach (var newItem in toAdd)
                //{
                //    if (!netChangeDict.ContainsKey(newItem.Pro_code))
                //        netChangeDict[newItem.Pro_code] = 0;
                //    netChangeDict[newItem.Pro_code] += newItem.Pro_sale_price;
                //}

                //// 处理修改的明细：计算新旧差值
                //foreach (var updateItem in toUpdate)
                //{
                //    var oldQty = oldDetails
                //        .FirstOrDefault(old => old.Sale_order_details_id == updateItem.Sale_order_details_id)?
                //        .Pro_sale_price ?? 0;

                //    if (!netChangeDict.ContainsKey(updateItem.Pro_code))
                //        netChangeDict[updateItem.Pro_code] = 0;

                //    netChangeDict[updateItem.Pro_code] += updateItem.Pro_sale_price - oldQty;
                //}

                //var productCodes = sinv_Sale_Order_Details.Select(d => d.Pro_code).Distinct().ToList();
                //var stocks = await myDbContext.inv_stock
                //    .Where(s => productCodes.Contains(s.pro_code))
                //    .ToDictionaryAsync(s => s.pro_code);

                //foreach (var (proCode, netChange) in netChangeDict)
                //{
                //    if (stocks.TryGetValue(proCode, out var stock))
                //    {
                //        stock.Stock_planned_outbound_qty += netChange; // 直接更新库存字段
                //        myDbContext.Entry(stock).State = EntityState.Modified;
                //    }
                //    else
                //    {
                //        // 若库存记录不存在，初始化新记录（根据业务需求）
                //        var newStock = new inv_stock
                //        {
                //            pro_code = proCode,
                //            Stock_planned_outbound_qty = netChange
                //        };
                //        myDbContext.inv_stock.Add(newStock);
                //    }
                //}
                //await myDbContext.SaveChangesAsync();

                await transaction.CommitAsync();
                return 1;
                //List<Sinv_Sale_Order_Details> sinv_Sale_Order_Details1 = await myDbContext.Sinv_Sale_Order_Details
                //    .Where(sod => sod.Sale_order_code == sinv_Sale_Order.Sale_order_code).ToListAsync();
                ////删除销售订单的原始明细
                //myDbContext.RemoveRange(sinv_Sale_Order_Details1);

                ////为销售详情表设置外键
                //foreach (var item in sinv_Sale_Order_Details)
                //{
                //    item.Sale_order_id = sinv_Sale_Order.Sale_order_id;
                //    item.Sale_order_code = sinv_Sale_Order.Sale_order_code;
                //}

                ////添加新的销售订单明细
                //myDbContext.AddRangeAsync(sinv_Sale_Order_Details);
                //await myDbContext.SaveChangesAsync();

                //await transaction.CommitAsync();
                //return 1;
            }
            catch (Exception)
            {
                await transaction.RollbackAsync();
                return 0;
            }
        }

        /// <summary>
        /// 检查字段是否被修改
        /// </summary>
        /// <param name="oldItem"></param>
        /// <param name="newItem"></param>
        /// <returns></returns>
        private bool IsModified(Sinv_Sale_Order_Details oldItem, Sinv_Sale_Order_Details newItem)
        {
            return oldItem.Pro_sale_qty != newItem.Pro_sale_qty ||
                   oldItem.Pro_sale_price != newItem.Pro_sale_price ||
                   oldItem.Pro_total_amount != newItem.Pro_total_amount ||
                   oldItem.Pro_cost_price != newItem.Pro_cost_price ||
                   oldItem.Pro_total_cost != newItem.Pro_total_cost ||
                   oldItem.Sale_order_details_id == newItem.Sale_order_details_id;
        }
    }
}
